package com.eastdigit.bpm.cmd;

import java.io.Serializable;

import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.pvm.runtime.InterpretableExecution;

public class ForceEndProcessInstanceCmd implements Command<Void>, Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -2551872862874924344L;

    protected String processInstanceId;
    protected String endReason;

    public ForceEndProcessInstanceCmd(String processInstanceId, String endReason) {
        this.processInstanceId = processInstanceId;
        this.endReason = endReason;
    }

    public Void execute(CommandContext commandContext) {
        if (processInstanceId == null) {
            throw new ActivitiIllegalArgumentException("processInstanceId is null");
        }

        // fill default reason if none provided
        if (endReason == null) {
            endReason = "ACTIVITI_FORCEEND";
        }

        ExecutionEntity execution = commandContext.getExecutionEntityManager().findExecutionById(processInstanceId);
        if (execution != null) {
            if (execution instanceof ExecutionEntity) {
                Context.getCommandContext().getHistoryManager().recordActivityEnd((ExecutionEntity) execution);
            }
            ((InterpretableExecution)execution).end();
        }

        return null;
    }

}
